//
//  Biuetooth.m
//  vidonn_bt_dll
//
//  Created by 曾 言伟 on 13-12-24.
//  Copyright (c) 2013年 vidonn. All rights reserved.
//

#import "X6Bluetooth.h"
#import "X6Bracelet.h"
#import "X6sysconfig.h"
#import "mode.h"

@implementation X6Bluetooth

@synthesize bracelets;
@synthesize CM;
@synthesize activePeripheral;
@synthesize Bdelegate;

- (id) init:(id) delegate;
{
    NSLog(@"进入到 X6Bluetooth --> - (id) init:(id) delegate;");
    self = [super init];
    if (self) {
        self.Bdelegate = delegate;
        self.CM = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        self.bracelets = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"进入到 X6Bluetooth --> - (void)centralManagerDidUpdateState:(CBCentralManager *)central");
    if (central.state != CBCentralManagerStatePoweredOn) {
        // In a real app, you'd deal with all the states correctly
        return;
    }
}

- (void)scan
{
    NSLog(@"进入到 X6Bluetooth --> - (void)scan");
    if (self->CM.state  != CBCentralManagerStatePoweredOn) {
        return;
    }
    
    
    [self.CM scanForPeripheralsWithServices:nil options:0];
    
    NSLog(@"Scanning started");
}

- (void)scanConnectedPeripheralsWithServices
{
    NSLog(@"进入到 X6Bluetooth --> - (void)scanConnectedPeripheralsWithServices");
    [self.bracelets removeAllObjects];
    // [self.CM retrieveConnectedPeripherals];
    NSArray *atmp = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"180a"],nil];
    NSArray *peripherals = [self.CM retrieveConnectedPeripheralsWithServices:atmp];
    for(int i = 0 ; i < peripherals.count; i++)
    {
        mode* md = [[mode alloc] init];
        md.Peripheral = ((CBPeripheral*)[peripherals objectAtIndex:i]);
        md.rssi = @"0";
        [self.bracelets addObject:md];
        [Bdelegate didSearchPeripheral:self.bracelets];
    }
    [self scan];
}

-(void) stopScan
{
    NSLog(@"进入到 X6Bluetooth --> -(void) stopScan");
    [self.CM stopScan];
    NSLog(@"Scanning stop");
}

- (void) disconnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"进入到 X6Bluetooth --> - (void) disconnectPeripheral:(CBPeripheral *)peripheral");
    [self.CM cancelPeripheralConnection:peripheral];
}

- (void) connectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"进入到 X6Bluetooth --> - (void) connectPeripheral:(CBPeripheral *)peripheral");
    [CM connectPeripheral:peripheral options:nil];
}

-(void) readValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p
{
    NSLog(@"进入到 X6Bluetooth --> -(void) readValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p");
    [p readValueForCharacteristic:chart];
}

-(void) WriteWithoutValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p value:(NSData*) value
{
    NSLog(@"进入到 X6Bluetooth --> -(void) WriteWithoutValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p value:(NSData*) value");
    [p writeValue:value forCharacteristic:chart type:CBCharacteristicWriteWithoutResponse];
}

-(void) WriteWithValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p value:(NSData*) value
{
    NSLog(@"进入到 X6Bluetooth --> -(void) WriteWithValuep:(CBCharacteristic *)chart p:(CBPeripheral*) p value:(NSData*) value");
    [p writeValue:value forCharacteristic:chart type:CBCharacteristicWriteWithResponse];
}

-(BOOL) isconnectPeripheral
{
    NSLog(@"进入到 X6Bluetooth --> -(BOOL) isconnectPeripheral");
    return  self.activePeripheral.state;
    //return iscon;
}

-(void) setnotiyf:(CBCharacteristic *)chart p:(CBPeripheral*) p
{
    NSLog(@"进入到 X6Bluetooth --> -(void) setnotiyf:(CBCharacteristic *)chart p:(CBPeripheral*) p");
    [p setNotifyValue:YES forCharacteristic:chart];
}

#pragma mark  蓝牙代理方法

- (void)centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals
{
    NSLog(@"进入到 X6Bluetooth --> - (void)centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals");
    for(int i = 0 ; i < peripherals.count; i++)
    {
        mode* md = [[mode alloc] init];
        md.Peripheral = ((CBPeripheral*)[peripherals objectAtIndex:i]);
        md.rssi = @"0";
        [self.bracelets addObject:md];
        [Bdelegate didSearchPeripheral:self.bracelets];
    }
    [self scan];
}

// 找到设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"进入到 X6Bluetooth 找到设备 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI");
    if(peripheral.name == nil)
        return;
    mode* md = [[mode alloc] init];
    md.Peripheral = peripheral;
    md.rssi = [RSSI stringValue];
    NSLog(@"蓝牙名称：%@，信号：%@",md.Peripheral,md.rssi);
    [self.bracelets addObject:md];
    if(self.bracelets.count >= 20)
        [self stopScan];
    [Bdelegate didSearchPeripheral:self.bracelets];
}

// 连接设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"进入到 X6Bluetooth 连接设备 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral");
    //NSLog(@"Peripheral Connected");
    self.activePeripheral = peripheral;
    peripheral.delegate = self;
    [self stopScan];
    [peripheral discoverServices:nil];
}

// 连接设备失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 连接设备失败 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error");
    NSLog(@"Failed to connect to %@. (%@)", peripheral, [error localizedDescription]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"diderror"
                                                        object:@"1"];
    
}

// 设备断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 设备断开连接 - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error");
    //NSLog(@"peripheral didDisconnectPeripheral");
    if (error) {
        //NSLog(@"Error didDisconnectPeripheral: %@", [error localizedDescription]);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"diderror"
                                                            object:@"2"];
    }
    [Bdelegate didDisConnectBracelet];
    
}

//寻找服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 寻找服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error");
    if (error)
    {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services)
    {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

//寻找子服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 寻找子服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error");
    if (error)
    {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        if((characteristic.properties & 0x10 ) == 0x10)
        {
            // [self setnotiyf:characteristic p:peripheral];
        }
    }
    [Bdelegate didConnectPeripheral:peripheral];
}

//读数据返回
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 读数据返回 - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)");
    if (error) {
        NSLog(@"Error didUpdateValueForCharacteristic: %@", [error localizedDescription]);
        return;
    }
    NSLog(@"Did read characteristic value : %@ with ID %@ %@", characteristic.value, characteristic.UUID,peripheral.identifier.UUIDString);
    [Bdelegate didRead:characteristic.value];
    return;
}

//通知返回
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 通知返回 - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error");
    if (error) {
        NSLog(@"Error changing notification state: %@", error.localizedDescription);
    }
    else
    {
        NSLog(@"Did write characteristic value : %@ with ID %@ %@", characteristic.value, characteristic.UUID,peripheral.identifier.UUIDString);
    }
    [Bdelegate didNotyf:(error == nil)];
}

//写 Characteristic 数据返回
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"进入到 X6Bluetooth 写 Characteristic 数据返回 - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error");
    NSLog(@"Did write characteristic value : %@ with ID %@", characteristic.value, characteristic.UUID);
    [Bdelegate didWrite:characteristic.value];
}

//写 Descriptor 数据返回
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
    NSLog(@"进入到 X6Bluetooth 写 Descriptor 数据返回 - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {");
    NSLog(@"Did write characteristic value : %@ with ID %@", descriptor.value, descriptor.UUID);
    NSLog(@"With error: %@", [error localizedDescription]);
}

@end

